import {
  getAllUserhttp,
  getOneUserhttp,
  putUserHttp,
  deleteUserHttp,
  putStateUserHttp,
} from '../../../../request/userHttp.js'
import { onMounted, computed, reactive } from 'vue'

export const superAdmin = () => {
  const centerDialogVisible = ref(false)
  const emodifyDialogVisible = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const small = ref(false)
  const background = ref(false)
  const disabled = ref(false)
  const tableData = ref([])
  const oneUser = ref()
  const searchvaule = ref('')
  const username = ref()
  const userpassword = ref()
  // 搜索
  function handleSearch(searchvaule) {
    getAllUserhttp(currentPage.value, pageSize.value, searchvaule).then(
      (res) => {
        tableData.value = res.data.result.data
      }
    )
  }

  // 显隐
  function handlexian() {
    centerDialogVisible.value = true
    allUser()
  }
  // 下一页
  const handleSizeChange = (val) => {
    pageSize.value = val
    allUser()
  }
  // 上一页
  const handleCurrentChange = (val) => {
    currentPage.value = val
    allUser()
  }

  // 获取分页用户信息
  const allUser = async () => {
    const res = await getAllUserhttp(currentPage.value, pageSize.value)
    tableData.value = res.data.result.data
  }
  // 修改
  async function handlEmodify(id) {
    emodifyDialogVisible.value = true
    const res = await getOneUserhttp(id)
    oneUser.value = res.data.result
    form.name = res.data.result.user_name
    form.psw = res.data.result.user_password
  }

  // 下线
  function handleStata(id, name, password) {
    putStateUserHttp(id, name, password)
    allUser()
  }

  // 删除
  function handleDelete(id) {
    deleteUserHttp(id)
    ElMessage({
      message: '删除用户成功',
      type: 'success',
    })
    allUser()
  }

  //表单校验
  const rules = ref({
    name: [
      {
        required: true,
        message: '用户名不能为空',
        tigger: 'blur',
      },
      {
        min: 3,
        max: 8,
        message: '用户名长度必须在3~8之间',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: '密码不能为空',
        tigger: 'blur',
      },
    ],
  })
  // 注册表单
  const form = reactive({
    name: '',
    psw: '',
  })

  //确定
  function handleConfirm() {
    emodifyDialogVisible.value = false
    const res = putUserHttp(oneUser.value.user_id, form.name, form.psw)
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
    allUser()
  }

  return {
    centerDialogVisible,
    emodifyDialogVisible,
    currentPage,
    pageSize,
    small,
    background,
    disabled,
    tableData,
    oneUser,
    searchvaule,
    handleSearch,
    handlexian,
    handleSizeChange,
    handleCurrentChange,
    allUser,
    handlEmodify,
    handleDelete,
    handleStata,
    rules,
    form,
    handleConfirm,
    username,
    userpassword,
  }
}
